package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 1.生成日期列表
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        log.info("日期列表：{}", dateList);

        // 2.构造营业额列表
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 当天00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));   // 当天23:59:59.999999999
            log.info("查询条件：{}", map);

            // 2.1 查询日期对应的营业额
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        log.info("营业额列表：{}", turnoverList);

        // 4.封装到VO并返回
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
        return vo;
    }

    /**
     * 用户数量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1.生成日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        log.info("日期列表：{}", dateList);

        // 2.构造用户数量列表
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 当天00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));   // 当天23:59:59.999999999
            log.info("查询条件：{}", map);

            // 2.1 查询日期对应的用户数量
            // select count(id) from user where create_time between #{} and #{}
            Integer newUserCount = userMapper.countByMap(map);
            newUserList.add(newUserCount);

            // 2.2 查询日期对应的总用户数量
            map.put("beginTime",null); // 当天起始时间设置为null，查询所有用户
            Integer totalUserCount = userMapper.countByMap(map);
            totalUserList.add(totalUserCount);
        }

        // 4.构造返回数据
        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();

        return vo;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        // 1.生成日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        log.info("订单统计-日期列表：{}", dateList);

        // 2.每日订单数
        List<Integer> orderCountList = new ArrayList<>(); // 每日订单总数
        List<Integer> validOrderCountList = new ArrayList<>(); // 每日有效订单总数
        int totalOrderCount = 0;  // 订单总数统计
        int validOrderCount = 0;  // 有效订单总数统计

        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("status", null);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 当天00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));   // 当天23:59:59.999999999
            log.info("订单查询条件：{}", map);

            // 2.1 查询日期对应的订单数量
            // 查询表：orders，条件：order_time>=当天起始时间，<= 当天结束时间
            Integer orderCount = ordersMapper.countByMap(map);
            orderCountList.add(orderCount);
            totalOrderCount += orderCount;

            // 3.每日有效订单数
            // 查询表：orders，条件：已完成订单，and order_time>=当天起始时间，<= 当天结束时间
            map.put("status", Orders.COMPLETED);
            log.info("订单查询条件：{}", map);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);
            validOrderCount += validOrder;
        }

        // 6.订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
        }

        // 7.封装到VO并返回
        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return vo;
    }

    /**
     * 销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO sailTop10(LocalDate begin, LocalDate end) {
        // 1.查询销量排名
        // 1.1 商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
        // 查询表:orders和order_detail,条件：日期范围，and 订单状态为已完成
        // 查询语句：select d.name,sum(d.number) from orders o, order_detail d where o.id = d.order_id group by d.name order by sum(d.number) desc limit 10;
        // 方法一
//         List<String> nameList = new ArrayList<>();   // 前十排名-名称
//         List numberList = new ArrayList<>(); // 前十排名-数量
//         Map map = new HashMap();
//         map.put("status", Orders.COMPLETED);
//         map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN)); // 当天00:00:00
//         map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));   // 当天23:59:59.999999999

        // 2.1 查询日期对应的订单数量
        // 查询表：orders，条件：order_time>=当天起始时间，<= 当天结束时间
//        List<Map> top10List = ordersMapper.top10(map);
//        nameList   = top10List.stream().map(item -> (String) item.get("name")).collect(Collectors.toList());
//        numberList = top10List.stream().map(item -> item.get("number")).collect(Collectors.toList());
//        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
//                .nameList(StringUtils.join(nameList, ","))
//                .numberList(StringUtils.join(numberList, ","))
//                .build();
//
//        return vo;

        // 方法二
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top10List = ordersMapper.getSalesTop10(beginTime, endTime);

        String nameList   = StringUtils.join(top10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(top10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        // 3.封装数据返回
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询近30天的运营数据
        LocalDate now = LocalDate.now();        // 2024-05-23
        LocalDate end = now.minusDays(1); // 2024-05-22
        LocalDate begin = now.minusDays(30);    // 2024-04-22
        // LocalDateTime end =
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // 2.往Excel表中写入数据
        // 根据类加载器读取项目中的模板文件, 基于模板文件创建Excel对象
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());    //营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());    //订单完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());    //新增用户数

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount()); //有效订单
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());       //平均客单价

            // 30天明细数据填充
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                beginTime = LocalDateTime.of(date, LocalTime.MIN); //4-23 00:00
                endTime = LocalDateTime.of(date, LocalTime.MAX);   //4-23 23:59:59.999999
                businessData = workspaceService.getBusinessData(beginTime, endTime);

                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3.通过输出流将Excel文件对象下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);

            // 4.释放资源
            os.close();
            workbook.close();
            is.close();
        } catch (IOException e) {
            log.error("文件写入失败！！！{}",e.getMessage());
        }
    }

    /**
     * 获取日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin,LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while(!begin.isAfter(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }
}
